package com.yc.resfoods.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.bean.Resuser;
import com.yc.resfoods.dao.ResuserDao;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import sun.plugin2.os.windows.SECURITY_ATTRIBUTES;


import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @ClassName a
 * @since: 2023/8/21 10:33
 * @auth: kirito
 * @description:
 * token: base64头部 base64 body  hs256 （base64头部 +base64 body，密钥）
 **/

@Configuration
public class JwtTokenUtil implements Serializable {
    //token有效期
    public static final long JWT_TOKEN_VALIDITY = 999 * 60 * 60;
    @Autowired
    private ResuserDao resuserDao;

    @Value("${jwt.secret}")//注入系统密钥属性
    private String secret;

    /**
     * 为用户生成token
     * 包装用户登录信息
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        //body 7个默认值  sub iss
        Map<String, Object> claims = new HashMap<>();
        //自己增加的body
        claims.put("username", userDetails.getUsername());
        claims.put("pwd", userDetails.getPassword());
        QueryWrapper<Resuser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userDetails.getUsername());
        wrapper.eq("pwd", userDetails.getPassword());
        Resuser user = this.resuserDao.selectOne(wrapper);
        claims.put("userid", user.getUserid());
        return doGenerateToken(claims, userDetails.getUsername());
    }

//    public static void main(String[] args) {
//        System.out.println(new BCryptPasswordEncoder().encode("a"));
//        UserDetails userDetails = new UserDetails() {
//            @Override
//            public Collection<? extends GrantedAuthority> getAuthorities() {
//                return null;
//            }
//
//            @Override
//            public String getPassword() {
//                return "a";
//            }
//
//            @Override
//            public String getUsername() {
//                return "a";
//            }
//
//            @Override
//            public boolean isAccountNonExpired() {
//                return false;
//            }
//
//            @Override
//            public boolean isAccountNonLocked() {
//                return false;
//            }
//
//            @Override
//            public boolean isCredentialsNonExpired() {
//                return false;
//            }
//
//            @Override
//            public boolean isEnabled() {
//                return true;
//            }
//        };
//        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
//        String token = jwtTokenUtil.generateToken(userDetails);
//        System.out.println(token);
//    }

    //获取jwt token用户名
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }
    // jwt token获取过期日期
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    // 从token获取calim
    private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimFromToken(token);
        return claimsResolver.apply(claims);
    }
    //利用secret密钥从token获取信息
    public Claims getAllClaimFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    //检测token是否过期
    public Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }



    /*创建token步骤
    1.定义令牌声明 入Issuer Expiration Subject ID
    2.使用HS512算法和密钥对jwt进行签名
    3.根据jws compact serialization 将jwt压缩为url安全字符
    */
    public String doGenerateToken(Map<String, Object> claims, String subject) {
        //构造器模式  claims就是一个map
        return Jwts.builder()
                //有效载荷
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis())) //token发布时间
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY *1000))
                //签名运算
                .signWith(SignatureAlgorithm.HS512, secret)
                //压缩
                .compact();
    }

    //检验token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        //用户名相同 且token未过期
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
}

